﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections.Generic;
using Sale_Operation;
using Sale_Common;
using Sale_Model;
using SaleSystem;
using ExtAspNet;


namespace SaleSystem.Business
{
    public partial class frm_BuyEdit : PageBase
    {
        #region Page Event
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                tb_BBDeta_PInfo_Id.OnClientTriggerClick = win_Content.GetSaveStateReference(tb_BBDeta_PInfo_Id.ClientID, this.hf_BBDeta_PInfo_Id.ClientID,this.nb_BBDeta_Count.ClientID, this.nb_BBDeta_CostPrice.ClientID, this.nb_BBDeta_Money.ClientID, this.nb_BBDeta_Price.ClientID)
                                         + win_Content.GetShowReference("~/ComPage/frm_ProductChooseList.aspx?PInfo_Id=");
                //tb_BBDeta_PInfo_Id.OnClientTriggerClick = win_Content.GetSaveStateReference(tb_BBDeta_PInfo_Id.ClientID, this.hf_BBDeta_PInfo_Id.ClientID)
                //         + win_Content.GetShowReference("~/ComPage/frm_ProductChooseList.aspx?PInfo_Id=" + this.tb_BBDeta_PInfo_Id.GetValueReference());
                InitControl();
                GetAndBind();
                bnImport.OnClientClick = win_Import.GetShowReference("~/ComPage/frm_PutInUploadList.aspx?Id=" + this.Id, "进货单明细导入");
            }
            if (Request[LinkService.RefreshTag] == "bnTotal")
            {
                bn_Total_Click(null, null);
            }
        } 
        protected void bnSave_Click(object sender, EventArgs e)
        {
            //如果是修改，保存前先校验下该单据状态是否已经被入库了，如果入库了则不能修改
            if (this.Id != 0)
            {
                BuyBill SM = new BuyBill();
                SM.BBill_Id = Id;
                Manager.GetModel(SM);
                if (SM.BBill_Input == 1)
                {
                    ExtAspNet.Alert.Show("该进货单已经入库，不能修改！", "操作提示！", MessageBoxIcon.Warning);
                    return;
                }
            }


            SModel.CreateMan = LinkService.GetCurrentUser().SUser_Id;
            SModel.CreateTime = System.DateTime.Now;
            SModel.State = 1;
            SModel.BBill_Code = this.tb_BBill_Code.Text;
            SModel.BBill_Count = ValueHandler.GetIntNumberValue(dtDetail.Compute("sum(BBDeta_Count)",""));
            SModel.BBill_Date = DateTime.Parse( tb_BBill_Date.Text);
            SModel.BBill_Id = this.Id;
            SModel.BBill_Memo = this.tb_BBill_Memo.Text;
            SModel.BBill_Money = ValueHandler.GetDecNumberValue( dtDetail.Compute("sum(BBDeta_Money)", ""));
            SModel.BBill_Supp_Id = ValueHandler.GetIntNumberValue( this.ddl_BBill_Supp_Id.SelectedValue);
            SModel.BBill_SUser_Id = ValueHandler.GetIntNumberValue(this.ddl_BBill_SUser_Id.SelectedValue);
            SModel.BBilll_PayType = ValueHandler.GetIntNumberValue(this.ddl_BBilll_PayType.SelectedValue);
            SModel.BBill_AList_Id = ValueHandler.GetIntNumberValue(this.ddl_BBill_AList_Id.SelectedValue);
            bool blHasExists = Manager.HasExists(SModel);
            if (blHasExists)
            {
                ExtAspNet.Alert.Show("进货单编码已经存在，请重新输入！", MessageBoxIcon.Information);
            }
            else
            {
                bool blRes = Manager.Save(SModel,dtDetail);
                if (blRes)
                    ExtAspNet.PageContext.RegisterStartupScript(ExtAspNet.ActiveWindow.GetHidePostBackReference(LinkService.RefreshString));

                else
                    ExtAspNet.Alert.Show("进货单信息编辑失败！", MessageBoxIcon.Error);
            }
        }
        protected void bn_Total_Click(object sender, EventArgs e)
        {
            SModel.BBill_Id = this.Id;
            Manager.GetModel(SModel);
            if (SModel.BBill_State == 1)
            {
                ExtAspNet.Alert.Show("该销售单已经结算，不能再次结算！", "操作提示！", MessageBoxIcon.Warning);
            }
            else
            {
                bool blRes = Manager.JS(SModel);
                if (blRes)
                {
                    PageContext.RegisterStartupScript(ExtAspNet.Alert.GetShowInTopReference("结算完成！", "操作提示！", MessageBoxIcon.Information) + ExtAspNet.ActiveWindow.GetHidePostBackReference(LinkService.RefreshString));
                }
                else
                {
                    ExtAspNet.Alert.Show("结算失败！", "操作提示！", MessageBoxIcon.Error);
                }
            }
        }
        protected void ddl_SBill_PayTypeSelectedChanged(object obj, EventArgs e)
        {
            SysConfig SM = new SysConfig();
            if (this.ddl_BBilll_PayType.SelectedValue == "1")//现金
            {
                SM.SConf_Id = 4;
            }
            else
                SM.SConf_Id = 5;
            SysConfigOp op = new SysConfigOp();
            op.GetConfig(SM);
            this.ddl_BBill_AList_Id.SelectedValue = SM.SConf_Value;
        }
        /// <summary>
        /// 添加产品明细
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnAdd_Click(object sender, EventArgs e)
        {
         
            if (hf_BBDeta_PInfo_Id.Text.Trim() == "")
            {
                ExtAspNet.Alert.Show("请先选中产品后再做此操作！", "提示！", MessageBoxIcon.Warning);
                return;
            }
            else
            {  
                DataTable dt = dtDetail;
                

                ProductInfoOp ProductManager = new ProductInfoOp();
                ProductInfo SM = new ProductInfo();
                SM.PInfo_Id = ValueHandler.GetIntNumberValue(hf_BBDeta_PInfo_Id.Text);
                //判断单据中是否存在该产品
                DataView dv = new DataView(dt);
                dv.RowFilter = "BBDeta_PInfo_Id=" + SM.PInfo_Id.ToString() + " AND BBDeta_Id<>" + BBDeta_Id;
                if (dv.Count > 0)
                {
                    ExtAspNet.Alert.Show("单据中已经存在该产品信息！", "提示！", MessageBoxIcon.Warning);
                    return;
                }
                DataRow dr = null;
                if (this.btnAdd.Text == "添加")
                {
                    dr = dt.NewRow();
                    dt.Rows.Add(dr);

                }
                else
                {
                    DataView dv0 = new DataView(dt);
                    dv0.RowFilter = "BBDeta_Id=" + BBDeta_Id;
                    if (dv0.Count > 0)
                        dr = dv0[0].Row;
                }
                ProductManager.GetModel(SM);
                dr["PInfo_Code"] = SM.PInfo_Code;
                dr["PInfo_Name"] = SM.PInfo_Name;
                dr["BBDeta_PInfo_Id"] = this.hf_BBDeta_PInfo_Id.Text;
                dr["BBDeta_SBill_Id"] = this.Id;
                dr["BBDeta_Count"] = ValueHandler.GetIntNumberValue(this.nb_BBDeta_Count.Text);
                dr["BBDeta_CostPrice"] = ValueHandler.GetDecNumberValue(this.nb_BBDeta_CostPrice.Text);
                dr["BBDeta_Price"] = ValueHandler.GetDecNumberValue(this.nb_BBDeta_Price.Text);
                dr["BBDeta_Money"] = ValueHandler.GetDecNumberValue(this.nb_BBDeta_CostPrice.Text) * ValueHandler.GetDecNumberValue(this.nb_BBDeta_Count.Text); 
                //获取产品类别
                ProductSortOp sortManager = new ProductSortOp();
                ProductSort sortSM = new ProductSort();
                sortSM.PSort_ID = SM.PInfo_PSort_ID;
                sortManager.GetModelById(sortSM);
                dr["PSort_Name"] = sortSM.PSort_Name;  
                gv_List.DataSource = dtDetail;
                gv_List.DataBind();
                gv_List.RecordCount = dtDetail.Rows.Count;
                //计算总数量及总金额
                tb_BBill_Count.Text = dt.Compute("sum(BBDeta_Count)", "").ToString();
                tb_BBill_Money.Text = dt.Compute("sum(BBDeta_Money)", "").ToString();
                ClearContent();
            }
        }
        protected void bnInput_Click(object sender, EventArgs e)
        {
            BuyBill bb = new BuyBill();
            bb.BBill_Id = this.Id;
            Manager.GetModel(bb) ;
            if (bb.BBill_Input == 1)
            {
                ExtAspNet.Alert.Show("该进货单已经入库，不能再次入库！", "操作提示！", MessageBoxIcon.Warning);
            }
            //else if (bb.BBilll_PayType == -1)
            //{
            //    ExtAspNet.Alert.Show("该单据结算方式并未保存，请保存后再入库！", "操作提示！", MessageBoxIcon.Warning);
            //    return;
            //}
            //else if (bb.BBill_AList_Id == 0 || bb.BBill_AList_Id == -1)
            //{
            //    ExtAspNet.Alert.Show("该单据结算账户并未保存，请保存后再入库！", "操作提示！", MessageBoxIcon.Warning);
            //    return;
            //}
            else
            {
                bool blRes= Manager.PutIn(bb);
                if (blRes)
                {
                    //bnSave.Enabled = false;
                    //bnInput.Enabled = false;
                    //btnAdd.Enabled = false;
                    //SimpleForm2.Hidden = true;
                    //gv_List.Columns[7].Hidden = true;
                    //gv_List.Columns[8].Hidden = true;
                    this.tb_BBill_Input.Text = "<span style='color:Green;font-weight:bold;'>已入库</span>";
                    PageContext.RegisterStartupScript(ExtAspNet.Alert.GetShowInTopReference("进货单入库完成！", "操作提示！", MessageBoxIcon.Information) + ExtAspNet.ActiveWindow.GetHidePostBackReference(LinkService.RefreshString));

                    
                }

            }
        }
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            ClearContent();
        
        }
        private void ClearContent()
        {
            this.tb_BBDeta_PInfo_Id.Text = "";
            this.hf_BBDeta_PInfo_Id.Text = "";
            this.nb_BBDeta_CostPrice.Text = "";
            this.nb_BBDeta_Count.Text = "1";
            this.nb_BBDeta_Money.Text = "";
            this.nb_BBDeta_Price.Text = "";
            BBDeta_Id = 0;
            this.btnAdd.Text = "添加";
            this.btnAdd.Icon = Icon.Add;
            this.btnCancle.Hidden = true;
        }
        protected void gv_List_RowCommand(object sender, ExtAspNet.GridCommandEventArgs e)
        {
            if (e.CommandName.ToLower() == "delete")
            {
                DataView dv = new DataView(dtDetail);
                BBDeta_Id = ValueHandler.GetIntNumberValue(gv_List.DataKeys[e.RowIndex][0]);
                dv.RowFilter = "BBDeta_Id=" + BBDeta_Id;
                if (dv.Count > 0)
                {
                    dv[0].Delete();
                }
                dtDetail.AcceptChanges();
                gv_List.DataSource = dtDetail;
                gv_List.DataBind();
                gv_List.RecordCount = dtDetail.Rows.Count;
                //计算总数量及总金额
                tb_BBill_Count.Text = dtDetail.Compute("sum(BBDeta_Count)", "").ToString();
                tb_BBill_Money.Text = dtDetail.Compute("sum(BBDeta_Money)", "").ToString();
                ClearContent();
            }
            else if (e.CommandName.ToLower() == "edit")
            {
                DataView dv = new DataView(dtDetail);
                BBDeta_Id = ValueHandler.GetIntNumberValue(gv_List.DataKeys[e.RowIndex][0]);
                dv.RowFilter = "BBDeta_Id=" + BBDeta_Id;
                if (dv.Count > 0)
                {
                    this.tb_BBDeta_PInfo_Id.Text = ValueHandler.GetStringValue( dv[0]["PInfo_Name"]);
                    this.hf_BBDeta_PInfo_Id.Text = ValueHandler.GetStringValue( dv[0]["BBDeta_PInfo_Id"]);
                    this.nb_BBDeta_CostPrice.Text = ValueHandler.GetDecNumberValue( dv[0]["BBDeta_CostPrice"]).ToString();
                    this.nb_BBDeta_Count.Text = ValueHandler.GetIntNumberValue(dv[0]["BBDeta_Count"]).ToString();
                    this.nb_BBDeta_Money.Text = ValueHandler.GetDecNumberValue(dv[0]["BBDeta_Money"]).ToString();
                    this.nb_BBDeta_Price.Text = ValueHandler.GetDecNumberValue(dv[0]["BBDeta_Price"]).ToString();
                    this.btnAdd.Icon = Icon.Accept;
                    this.btnAdd.Text = "确定";
                    this.btnCancle.Hidden = false;
                } 
            }
        }

        protected void gv_List_PageIndexChange(object sender, ExtAspNet.GridPageEventArgs e)
        {
            gv_List.PageIndex = e.NewPageIndex;
            SortPags sp = new SortPags(dtDetail);
            gv_List.DataSource = sp.GetCurrentPage(LinkService.PageSize, gv_List.PageIndex + 1);
            gv_List.DataBind();
        }
 
        #endregion

        #region Method
        private void InitControl()
        {

            if (Request["Id"] != null)
            {
                Id = ValueHandler.GetIntNumberValue(Request["Id"]);
            }
            bnClose.OnClientClick = ExtAspNet.ActiveWindow.GetHideReference();
            bn_Total.OnClientClick = win_Confirm.GetShowReference("~/Other/frm_TotalEdit.aspx?Type=1&Id=" + this.Id, "结算方式确认") + ";return false";
            SysUsersOp userManager = new SysUsersOp();
            DataTable dtUser= userManager.GetList("");
            this.ddl_BBill_SUser_Id.DataSource = dtUser;
            this.ddl_BBill_SUser_Id.DataBind();
            this.ddl_BBill_SUser_Id.Items.Insert(0, new ExtAspNet.ListItem("-未选择-", "-1"));
            SupplierOp supplierManager = new SupplierOp();
            DataTable dtSupplier = supplierManager.GetList("");
            this.ddl_BBill_Supp_Id.DataSource = dtSupplier;
            this.ddl_BBill_Supp_Id.DataBind();
            this.ddl_BBill_Supp_Id.Items.Insert(0, new ExtAspNet.ListItem("-未选择-", "-1"));
            this.ddl_BBill_SUser_Id.SelectedValue = LinkService.GetCurrentUser().SUser_Id.ToString();
            //结算方式

            this.ddl_BBilll_PayType.DataSource = LinkService.GetPayType();
            this.ddl_BBilll_PayType.DataBind();
            this.ddl_BBilll_PayType.Items.Insert(0, new ExtAspNet.ListItem("-未选择-", "-1"));
            //结算状态
            //this.ddl_SBill_State.DataSource = LinkService.GetSBill_State();
            //this.ddl_SBill_State.DataBind();
            //this.ddl_SBill_State.Items.Insert(0, new ExtAspNet.ListItem("-未选择-", "-1"));
            //账户
            AccountListOp AccountManager = new AccountListOp();
            DataTable dtAccountList = AccountManager.GetList("");
            this.ddl_BBill_AList_Id.DataSource = dtAccountList;
            this.ddl_BBill_AList_Id.DataBind();
            this.ddl_BBill_AList_Id.Items.Insert(0, new ExtAspNet.ListItem("-未选择-", "-1"));
          

        }
        private void GetAndBind()
        {
            SModel.BBill_Id = Id;
            dtDetail = Manager.GetDetail(SModel) ;
            this.tb_BBill_Code.Text = SModel.BBill_Code;
            this.tb_BBill_Count.Text = SModel.BBill_Count.ToString();
            this.tb_BBill_Date.Text = ValueHandler.GetStringShortDateValue(SModel.BBill_Date);
            if (SModel.BBill_Input == 1)
            {

                this.tb_BBill_Input.Text = "<span style='color:Green;font-weight:bold;'>已入库</span>";
            }
            else
                this.tb_BBill_Input.Text = "<span style='color:Red;font-weight:bold;'>未入库</span>";
            if (SModel.BBill_State == 1)
            {
                this.tb_BBill_State.Text = "<span style='color:Green;font-weight:bold;'>已结算</span>";
            }
            else
                this.tb_BBill_State.Text = "<span style='color:Red;font-weight:bold;'>未结算</span>";

            this.tb_BBill_Memo.Text = SModel.BBill_Memo;
            this.tb_BBill_Money.Text = SModel.BBill_Money.ToString();
            this.ddl_BBill_Supp_Id.SelectedValue = SModel.BBill_Supp_Id.ToString();
            this.ddl_BBill_SUser_Id.SelectedValue = SModel.BBill_SUser_Id.ToString();
            this.ddl_BBill_AList_Id.SelectedValue = SModel.BBill_AList_Id.ToString();
            this.ddl_BBilll_PayType.SelectedValue = SModel.BBilll_PayType.ToString();
            SortPags sp = new SortPags(dtDetail);
            gv_List.DataSource = sp.GetCurrentPage(LinkService.PageSize,gv_List.PageIndex+1);
            gv_List.DataBind();
            gv_List.RecordCount = dtDetail.Rows.Count;
            if (Id != 0)
            {
                //已结算
                if (SModel.BBill_State == 1)
                {
                    bnSave.Enabled = false;
                    bnInput.Enabled = false;
                    btnAdd.Enabled = false;
                    this.bnImport.Enabled = false;
                    this.bn_Total.Enabled = false;                 
                    SimpleForm2.Hidden = true;
                    gv_List.Columns[7].Hidden = true;
                    gv_List.Columns[8].Hidden = true;
                }
                else//未结算
                {
                    //未入库
                    if (SModel.BBill_Input == 0)
                    {
                        bnSave.Enabled = true;
                        bnInput.Enabled = true;
                        this.bnImport.Enabled = true;
                        this.bn_Total.Enabled=false;
                    }
                    else//已入库
                    {
                        this.bnSave.Enabled = false;
                        bnInput.Enabled = false;
                        btnAdd.Enabled = false;
                        this.bnImport.Enabled = false;
                        SimpleForm2.Hidden = true;
                        gv_List.Columns[7].Hidden = true;
                        gv_List.Columns[8].Hidden = true;

                    } 
                }
               
            }
            else
            {
                this.tb_BBill_Code.Text = Coder.CreateCoder(EMenuList.进货单管理);
                this.bnImport.Enabled = false;
                this.bnInput.Enabled = false;
                this.bn_Total.Enabled = false;
                tb_BBill_Date.Text = ValueHandler.GetStringValue(System.DateTime.Now.ToString("yyyy-MM-dd"));


            }
            this.bnImport.ToolTip = "只有在编辑状态下才可导入！";
            this.bnInput.ToolTip = "只有在编辑状态下才可入库！";
            this.bnSave.ToolTip = "只有未入库的才可保存！";
            this.bn_Total.ToolTip = "只有入库的进货单才可结算！";
        }

        #endregion

        #region Property
        BuyBillOp Manager = new BuyBillOp();
        new Sale_Model.BuyBill SModel = new Sale_Model.BuyBill();
        public DataTable dtDetail
        {
            get
            {
                return ViewState["dtDetail"] as DataTable;
            }
            set
            {
                ViewState["dtDetail"] = value;
            }
        }
        /// <summary>
        /// 子表当前编辑的关键子
        /// </summary>
        public int BBDeta_Id
        {
            get
            {
                return ValueHandler.GetIntNumberValue(ViewState["BBDeta_Id"]);
            }
            set
            {
                ViewState["BBDeta_Id"] = value;
            }
        }
        #endregion

      

  

    
    }
}
